'use server';

import { db } from '@/lib/db';
import { createToken } from '@/lib/jwt';
import { LoginSchema, RegisterSchema } from '@/schemas';
import { getUserByEmail } from '@/server/controllers/userController';
import bcrypt from 'bcryptjs';

export const login = async (values) => {
    const validatedFields = LoginSchema.safeParse(values);
    // console.log(validatedFields);
    if (!validatedFields.success) {
        return { error: '输入无效' };
    }
    const { user_email, user_password } = validatedFields.data;

    const user = await getUserByEmail(user_email);

    if (!user || !user.user_password) return { error: '无效账号' };

    const passwordMatched = await bcrypt.compare(user_password, user.user_password);
    if (!passwordMatched) {
        return { error: '用户名/密码错误' };
    }
    const jwtToken = await createToken(user);
    return { success: '登录成功' };
};

export const register = async (values) => {
    const validatedFields = RegisterSchema.safeParse(values);
    if (!validatedFields.success) {
        return { error: 'Invalid email or password or nickname' };
    }
    const { user_email, user_password, user_name } = validatedFields.data;
    const salt = 14;
    const hashedPassword = await bcrypt.hash(user_password, salt);
    const existingUser = await getUserByEmail(user_email);
    if (existingUser) return { error: '邮件已存在!' };
    await db.tb_user.create({
        data: {
            user_name,
            user_email,
            user_password: hashedPassword
        }
    });
    // TODO: Send verification token email
    // console.log(user_email, user_name, hashedPassword);

    return { success: '注册成功' };
};
